﻿using System.Collections;
using System.Collections.Generic;

using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public static class UGUIEventTriggerHelper
{
    public static void AddListener(GameObject go, EventTriggerType eventID, UnityAction<BaseEventData> callback)
    {
        var eventTrigger = go.GetComponent<EventTrigger>();

        if (eventTrigger == null)
        {
            eventTrigger = go.AddComponent<EventTrigger>();
        }

        var triggers = eventTrigger.triggers;

        if (triggers == null)
        {
            eventTrigger.triggers = triggers = new List<EventTrigger.Entry>();
        }

        EventTrigger.Entry entry = null;

        for (int i = 0; i < triggers.Count; i++)
        {
            if (triggers[i].eventID == eventID)
            {
                entry = triggers[i];
                break;
            }
        }

        if (entry == null)
        {
            triggers.Add(entry = new EventTrigger.Entry()
            {
                eventID = eventID
            });
        }

        var triggerEvent = entry.callback;

        if (triggerEvent == null)
        {
            entry.callback = triggerEvent = new EventTrigger.TriggerEvent();
        }

        triggerEvent.AddListener(callback);
    }

    public static void RemoveListener(GameObject go, EventTriggerType eventID, UnityAction<BaseEventData> callback)
    {
        var eventTrigger = go.GetComponent<EventTrigger>();

        if (eventTrigger == null)
        {
            return;
        }

        var triggers = eventTrigger.triggers;

        if (triggers == null)
        {
            return;
        }

        EventTrigger.Entry entry = null;

        for (int i = 0; i < triggers.Count; i++)
        {
            if (triggers[i].eventID == eventID)
            {
                entry = triggers[i];
                break;
            }
        }

        if (entry == null)
        {
            return;
        }

        var triggerEvent = entry.callback;

        if (triggerEvent == null)
        {
            return;
        }

        triggerEvent.RemoveListener(callback);
    }
}
